package com.bangdream.michelia.tool.retrofithttp.picasso;

import android.content.Context;
import android.net.Uri;

import com.squareup.picasso.Downloader;
import com.squareup.picasso.NetworkPolicy;
import com.bangdream.michelia.utils.MyLog;

import java.io.IOException;

import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;

/**
 * Created by Administrator on 2017/1/11.
 * 图片下载的okhttp配置
 */

public class ImageDownLoader implements Downloader {
	private final static String TAG = "ImageDownLoader";
	private OkHttpClient client = null;
	private String cookie;
	private String sessionid = "";
	public ImageDownLoader(Context context) {
		this.cookie = sessionid = "";
		//MyLog.e(TAG,"Cookie："+cookie);
	}

	public ImageDownLoader(Context context, OkHttpClient client) {
		this.cookie = sessionid = "";
		this.client = client;
	}

	@Override
	public Response load(Uri uri, int networkPolicy) throws IOException {

		MyLog.e(TAG,"Cookie："+cookie);
		CacheControl cacheControl = null;
		if (networkPolicy != 0) {
			if (NetworkPolicy.isOfflineOnly(networkPolicy)) {
				cacheControl = CacheControl.FORCE_CACHE;
			} else {
				CacheControl.Builder builder = new CacheControl.Builder();
				if (!NetworkPolicy.shouldReadFromDiskCache(networkPolicy)) {
					builder.noCache();
				}
				if (!NetworkPolicy.shouldWriteToDiskCache(networkPolicy)) {
					builder.noStore();
				}
				cacheControl = builder.build();
			}
		}
		Request.Builder builder;
		if(cookie!=null) {
			builder = new Request.Builder()
					.addHeader("cookie", cookie)
					.removeHeader("User-Agent")
					.url(uri.toString());
		}
		else
		{
			builder = new Request.Builder()
					.url(uri.toString());
		}
		if (cacheControl != null) {
			builder.cacheControl(cacheControl);
		}

		okhttp3.Response response = client.newCall(builder.build()).execute();
		int responseCode = response.code();
		if (responseCode >= 300) {
			response.body().close();
			throw new ResponseException(responseCode + " " + response.message(), networkPolicy,
					responseCode);
		}
		boolean fromCache = response.cacheResponse() != null;
		ResponseBody responseBody = response.body();
		return new Response(responseBody.byteStream(), fromCache, responseBody.contentLength());
	}

	@Override
	public void shutdown() {

		Cache cache = client.cache();
		if (cache != null) {
			try {
				cache.close();
			} catch (IOException ignored) {

			}
		}
	}
//	@Override
//	protected HttpURLConnection createConnection(String url, Object extra) throws IOException {
//		MyLog.e(TAG,"Cookie：==="+sessionid);
//		//super.createConnection(url,extra);
//		HttpURLConnection connection = super.createConnection(url, extra);
//		connection.setRequestProperty("Cookie", extra.toString());//extra就是SessionId，何时传入，见第三步
//		connection.connect();
//		return connection;
//	}
}